package com.ht.api.controller;

import java.util.Map;
import java.util.Random;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ht.api.annotate.OpenApi;
import com.ht.api.bean.AjaxResult;
import com.ht.api.open.OpenUtil;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * 测试
 * @author asq
 * @createTime 2024年12月21日 20:21:44
 */
@Controller
@Slf4j
public class TestController {
	/** 用户ID：asq */
	private static String USER_ID = "wmFibqCgAAKJoyRahfbGpmU4h4-cy1AA";
	/** 用户ID：gaoxian */
//	private static String USER_ID = "wmFibqCgAAMg21CPspgol5Ga3tTZhXMw";
	/** 客服ID */
	private static String KF_ID = "wkFibqCgAAooZu1Zlww4aycDtB-l9rBQ";
	/** 应用：花田心选 */
	private static String APP_ID = "1876990838014349312";
	/** 接口：发送消息 */
	private static long API_ID_SEND = 1891365068554244096L;
	/** 接口：结束会话 */
	private static long API_ID_OVER = 1891363818706178048L;
	
    @GetMapping("/test")
    @OpenApi
    public String testForm(Model model) {
    	log.info("收到请求，随机数：{}", new Random().nextFloat());
    	
        return "test";
    }
    
    @PostMapping("/send")
    @ResponseBody
    @OpenApi
    public AjaxResult sendMessage(@RequestBody Map<String, String> params) {
    	String message = params.get("message");
    	
		// 调用微信接口，发送消息
		JSONObject json = JSONUtil.createObj();
		json.set("touser", USER_ID);
		json.set("open_kfid", KF_ID);
		json.set("msgtype", "text");
		json.set("text", JSONUtil.createObj().set("content", message));
		String msgs = OpenUtil.call(APP_ID, API_ID_SEND, json);
		
		// 解析接口返回结果
		JSONObject result = JSONUtil.parseObj(msgs);
		String errmsg = result.getStr("errmsg");
		if (result.getInt("errcode") == 0) {
			return AjaxResult.success(errmsg);
		} else {
			return AjaxResult.error(errmsg);
		}
    }
    
    @PostMapping("/over")
    @ResponseBody
    @OpenApi
    public AjaxResult serviceover() {
    	
		// 调用微信接口，发送消息
		JSONObject json = JSONUtil.createObj();
		json.set("open_kfid", KF_ID);
		json.set("external_userid", USER_ID);
		json.set("service_state", 4);
		String msgs = OpenUtil.call(APP_ID, API_ID_OVER, json);
		
		// 解析接口返回结果
		JSONObject result = JSONUtil.parseObj(msgs);
		String errmsg = result.getStr("errmsg");
		if (result.getInt("errcode") == 0) {
			return AjaxResult.success(errmsg);
		} else {
			return AjaxResult.error(errmsg);
		}
    }
}
